from typing import Optional
from sqlalchemy.exc import IntegrityError
from sqlmodel import Session
from .base import CRUDBase
from app import models
from app.core.security import get_password_hash

class EmailAlreadyExistsError(Exception):
    pass


class User(CRUDBase[models.User, models.UserCreate, models.UserProfileUpdateMe]):
    def __init__(self, db: Session):
        super().__init__(db)
        self.model = models.User

    async def create(self, data: models.UserCreate) -> models.User:
        try:
            db_obj = models.User.model_validate(
                data, update={"hashed_password": get_password_hash(data.password)}
            )
            return await super().create(db_obj)
        except IntegrityError as e:
            if "UniqueViolationError" in str(object=e) and "email" in str(object=e):
                raise EmailAlreadyExistsError(
                    f"User with this email already exists. Try signing in with your original SSO provider."
                ) from e
            raise e
    async def update_password(self, data: models.UpdatePassword) -> models.User:
        try:
            obj= models.User.model_validate(self.model,update={"hashed_password": get_password_hash(data.new_password  )         })  
            return await super().update(models.User, obj)
        except IntegrityError as e:            
            raise e
